# coding: utf8
import re
import amazonproduct    
import sys, os

if cfg.aws_enable:
    _aws_ns = {'aws': 'http://webservices.amazon.com/AWSECommerceService/2009-10-01'}
    _aws_api = amazonproduct.API(cfg.aws_id, cfg.aws_key, locale='us')

# options for <select> fields
GENRE_CHOICES = (
    'Sci-Fi/Fantasy',
    T('Police Procedurals'),
    'Textbook',
    'Religious',
    'Self-Help',
    'Comic',
    'Poetry',
    'Action/Adventure',
    'General',
    'Writing Reference',
    'General Reference',
    'Cookbook'
)

CLASSIF_CHOICES = [
    'Adult',
    'Young Adult',
    'Child - Chapter',
    'Child - Picture']
    
AGELVL_CHOICES = [
    'Adult',
    'Young Adult',
    'Intermediate',
    'Primary']

COND_CHOICES = [
    'Excellent',
    'Good',
    'Fine',
    'Poor']

#table declarations
db.define_table("books",
    Field("isbn", "string", label="ISBN", length=20, default=None),
    Field("author", "string", length=50, notnull=True, default=None),
    Field("title", "string", length=100, notnull=True, default=None),
    Field("illustrator", "string", length=50, default=None),
    Field("series", "string", length=100, default=None),
    Field("place", "integer", label="Place in Series", length=3, default=0),
    Field("publisher", "string", length=30, default=None),
    Field("genre", "string", length=20, notnull=True, default=None, requires=IS_IN_SET(GENRE_CHOICES)),
    Field("classification", "string", notnull=True, default=None, requires=IS_IN_SET(CLASSIF_CHOICES)),
    Field("age_level", "string", notnull=True, default=None, requires=IS_IN_SET(AGELVL_CHOICES)),
    Field("copyright", "integer", length=4, default=None),
    Field("edition", "integer", length=2, default=None),
    Field("num_copies", "integer", label='No. of Copies', notnull=True, default=1),
    Field("awards", "string", length=50, default=None),
    Field("language", "string", length=20, notnull=True, default=None),
    Field("condition", "string", length=10, notnull=True, default=None, requires=IS_IN_SET(COND_CHOICES)),
    Field("signed", "boolean", label='Signed', notnull=True, default=False, requires=False),
    Field("antique", "boolean", label='Antique', notnull=True, default=False, requires=False),
    Field("comments", "text", default=None))

from datetime import datetime

db.define_table("loans",
    Field("id_books", db.books),
    Field("name", "string", length=50, notnull=True, default=None),
    Field("lndate", "date", label='Date of Loan:', notnull=True, default=datetime.now()),
    Field("comments", "text", default=None, notnull=False))

# define relation between loans and books
db.loans.id_books.requires=IS_IN_DB(db, 'books.id', '%(author)s %(title)s')



def book_search(kwds):
    if cfg.aws_enable:
        if len(kwds):
            terms = []
            for k in kwds:
                terms.append(k + ':' + kwds[k])
                pwrsrch = ' and '.join(terms)
                nodes = _aws_api.item_search('Books', ResponseGroup='ItemAttributes', Power=pwrsrch)
                books = []
            for book in nodes.xpath('//aws:Items/aws:Item', namespaces=_aws_ns):
                try:
                    books.append((book.ItemAttributes.Author, book.ItemAttributes.Title, "%010d" % book.ItemAttributes.ISBN.pyval))
                except:
                    books.append((book.ItemAttributes.Author, book.ItemAttributes.Title, 'ASIN:%s' % book.ASIN))
            return books
        else:
            return None
    else:
        return None

def item_lookup(isbn):
    if cfg.aws_enable:
        if isbn.startswith('ASIN:'):
            asin = isbn.split(':')[1]
            node = _aws_api.item_lookup(asin, ResponseGroup='ItemAttributes')
        else:
            newisbn = ''.join(isbn.split('-'))
            node = _aws_api.item_lookup(newisbn, IdType='ISBN', SearchIndex='Books', ResponseGroup='ItemAttributes')
        nodeatts = node.xpath('//aws:ItemAttributes', namespaces=_aws_ns)
        book = {'author': nodeatts[0].Author}
        book['title'] = nodeatts[0].Title
        try:
            book['isbn'] = nodeatts[0].ISBN
        except:
            book['isbn'] = ''
        book['publisher'] = nodeatts[0].Publisher
        book['copyright'] = nodeatts[0].PublicationDate.pyval.split('-')[0]
        return book
    else:
        return None
